package com.mrd.shiptask_shipowner.activity;

import com.mrd.shiptask_shipowner.R;
import com.mrd.shiptask_shipowner.constants.HttpConstant;
import com.mrd.shiptask_shipowner.constants.database.DBUtil;
import com.mrd.shiptask_shipowner.serviecs.initdatadao.InitDatasDaoImpl;
import com.mrd.shiptask_shipowner.shiareutil.SharePreferenceUtil;
import com.mrd.shiptask_shipowner.unit_tools.FunctionOfActivity;
import com.mrd.shiptask_shipowner.unit_tools.SysApplication;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class NewShipOrderActivity extends Activity {

	private final NewShipOrderActivity THIS = NewShipOrderActivity.this;
	private EditText dunWeiEt, huoWuEt, minPiceEt, maxPiceEt;
	private Button qiYunDiEt, jiChuanGangEt, jiChuanRiQiBt, youXiaoQiZhiBt,
			baoCunBt, tiJiaoBt, muDiDiEt;
	private Button backToBeforeBt;
	private SharePreferenceUtil spu;
	private static ProgressDialog progressDialog;
	private LinearLayout ll;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ship_new_order);
		progressDialog = new ProgressDialog(THIS);
		spu = new SharePreferenceUtil(THIS, HttpConstant.SAVE_USER);
		initViewAction();
		SysApplication.getInstance().addActivity(this);

	}

	private void initViewAction() {
		TextView topTitleTv = (TextView) findViewById(R.id.topTitleTv);
		topTitleTv.setText("新建船源");
		baoCunBt = (Button) findViewById(R.id.baocun);
		tiJiaoBt = (Button) findViewById(R.id.tijiao);
		baoCunBt.setOnClickListener(ocl);
		tiJiaoBt.setOnClickListener(ocl);
		jiChuanGangEt = (Button) findViewById(R.id.jichuangang);
		dunWeiEt = (EditText) findViewById(R.id.dunwei);
		dunWeiEt.setInputType(EditorInfo.TYPE_CLASS_PHONE);
		huoWuEt = (EditText) findViewById(R.id.huowu);
		minPiceEt = (EditText) findViewById(R.id.minPice);
		maxPiceEt = (EditText) findViewById(R.id.maxPice);
		minPiceEt.setInputType(EditorInfo.TYPE_CLASS_PHONE);
		maxPiceEt.setInputType(EditorInfo.TYPE_CLASS_PHONE);
		qiYunDiEt = (Button) findViewById(R.id.qiyundi);
		muDiDiEt = (Button) findViewById(R.id.mudidi);

		jiChuanRiQiBt = (Button) findViewById(R.id.jichuanriqi);
		youXiaoQiZhiBt = (Button) findViewById(R.id.youxiaoqizhi);
		jiChuanRiQiBt.setOnClickListener(ocl);
		youXiaoQiZhiBt.setOnClickListener(ocl);
		jiChuanGangEt.setOnClickListener(ocl);
		qiYunDiEt.setOnClickListener(ocl);
		muDiDiEt.setOnClickListener(ocl);

		if (getIntent().hasExtra("bianji")
				&& getIntent().getExtras().getBoolean("bianji")) {

			jiChuanGangEt
					.setText(getIntent().hasExtra("getEShipPort") == false ? ""
							: getIntent().getStringExtra("getEShipPort"));
			dunWeiEt.setText(getIntent().hasExtra("loadton") == false ? ""
					: getIntent().getStringExtra("loadton"));
			huoWuEt.setText(getIntent().hasExtra("getGoodsType") == false ? ""
					: getIntent().getStringExtra("getGoodsType"));
			qiYunDiEt
					.setText(getIntent().hasExtra("getStartPort") == false ? ""
							: getIntent().getStringExtra("getStartPort"));
			muDiDiEt.setText(getIntent().hasExtra("getEndPort") == false ? ""
					: getIntent().getStringExtra("getEndPort"));

			jiChuanRiQiBt
					.setText(getIntent().hasExtra("getEShipTime") == false ? ""
							: getIntent().getStringExtra("getEShipTime"));
			youXiaoQiZhiBt
					.setText(getIntent().hasExtra("getEndTime") == false ? ""
							: getIntent().getStringExtra("getEndTime"));
			minPiceEt.setText(getIntent().hasExtra("minPice") == false ? ""
					: getIntent().getStringExtra("minPice"));
			maxPiceEt.setText(getIntent().hasExtra("maxPice") == false ? ""
					: getIntent().getStringExtra("maxPice"));

		}
		String getId = getIntent().hasExtra("getId") == false ? System
				.currentTimeMillis() + "" : getIntent().getStringExtra("getId");
		spu.setShipOrderTaskId(getId);

		ll = (LinearLayout) findViewById(R.id.ll1);
		ll.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				ll.setFocusable(true);
				ll.setFocusableInTouchMode(true);
				ll.requestFocus();
				InputMethodManager imm = (InputMethodManager) THIS
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(ll.getWindowToken(), 0);
				return false;
			}
		});
		backToBeforeBt = (Button) findViewById(R.id.backToBeforeBt20);
		backToBeforeBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				FunctionOfActivity.progressDialogShow(THIS);
				startActivity(new Intent(THIS, ShipOrderActivity.class));
			}
		});
	}

	public final OnClickListener ocl = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.jichuanriqi:
				try {
					initWheelDate(jiChuanRiQiBt);
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case R.id.youxiaoqizhi:
				try {
					initWheelDate(youXiaoQiZhiBt);
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case R.id.baocun:
				try {
					if (isAllInfoValues()) {
						if (qiYunDiEt.getText().toString().length() <= 0
								|| jiChuanRiQiBt.getText().toString().length() <= 0) {
							if (jiChuanRiQiBt.getText().toString().length() <= 0) {
								FunctionOfActivity.makeToaskShow(THIS,
										"吉船日期不能为空");
							} else if (qiYunDiEt.getText().toString().length() <= 0) {
								FunctionOfActivity.makeToaskShow(THIS,
										"起运地不能为空");
							}

						} else {
							progressDialog.setMessage("保存中···");
							progressDialog.show();
							String emptyShipPortText = jiChuanGangEt.getText()
									.toString();
							String emptyShipDateText = jiChuanRiQiBt.getText()
									.toString();
							String unitTypeText = dunWeiEt.getText().toString();
							String goodsTypeText = huoWuEt.getText().toString();
							String startPortText = qiYunDiEt.getText()
									.toString();
							String endPortText = muDiDiEt.getText().toString();
							String effectiveDateText = youXiaoQiZhiBt.getText()
									.toString();
							String shipId = spu.getShip_id();
							// 0代表保存（草稿），1代表提交
							String state = "0";
							String minPice = minPiceEt.getText().toString();
							String maxPice = maxPiceEt.getText().toString();
							// 价格区间中某项不填，则随意给个默认值，为配合服务器检查参数规则
							// if (minPiceEt.getText().length() <= 0) {
							// minPice = "0.1";
							// }
							// if (maxPiceEt.getText().length() <= 0) {
							// maxPice = "1000";
							// }
							DBUtil.deleteShipOrderTableByStatus(THIS, "0",
									spu.getShipOrderTaskId());
							DBUtil.insertIntoTableForSave(THIS, shipId, state,
									emptyShipPortText, emptyShipDateText,
									unitTypeText, goodsTypeText, startPortText,
									endPortText, effectiveDateText,
									spu.getShipOrderTaskId(), "", "", minPice,
									maxPice);
							// InitDatasShipOrderListActivity
							// .LoadShipOrderActivityDatas(THIS);
							startActivity(new Intent(THIS,
									ShipOrderActivity.class));
						}
					} else {
						FunctionOfActivity.makeToaskShow(THIS, "还有选项未填");
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case R.id.tijiao:
				try {
					if (isAllInfoValues()) {
						if (qiYunDiEt.getText().toString().length() <= 0
								|| jiChuanRiQiBt.getText().toString().length() <= 0) {
							if (jiChuanRiQiBt.getText().toString().length() <= 0) {
								FunctionOfActivity.makeToaskShow(THIS,
										"吉船日期不能为空");
							} else if (qiYunDiEt.getText().toString().length() <= 0) {
								FunctionOfActivity.makeToaskShow(THIS,
										"起运地不能为空");
							}
						} else {
							submitAction();
						}
					} else {
						FunctionOfActivity.makeToaskShow(THIS, "还有选项未填");
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case R.id.jichuangang:
				// FunctionOfActivity.progressDialogShow(THIS);
				Intent intent = new Intent(THIS, PortMnuActivity.class);
				startActivityForResult(intent, 1);
				break;
			case R.id.qiyundi:
				// FunctionOfActivity.progressDialogShow(THIS);
				Intent intent1 = new Intent(THIS, PortMnuActivity.class);
				startActivityForResult(intent1, 2);
				break;
			case R.id.mudidi:
				// FunctionOfActivity.progressDialogShow(THIS);
				Intent intent2 = new Intent(THIS, PortMnuActivity.class);
				startActivityForResult(intent2, 3);
				break;
			default:
				break;
			}
		}

		private boolean isAllInfoValues() {
			// TODO Auto-generated method stub
			if (jiChuanGangEt.getText().length() > 0
					&& dunWeiEt.getText().length() > 0
					&& huoWuEt.getText().length() > 0
					&& qiYunDiEt.getText().length() > 0
					&& muDiDiEt.getText().length() > 0
					&& jiChuanRiQiBt.getText().length() > 0
					&& youXiaoQiZhiBt.getText().length() > 0) {
				return true;
			}
			return false;
		}

	};

	private void submitAction() {
		try {
			String getLoadton = dunWeiEt.getText().toString();
			String getStartPort = qiYunDiEt.getText().toString();
			String getEndPort = muDiDiEt.getText().toString();
			String getEndTime = youXiaoQiZhiBt.getText().toString();
			String getCargoTypes = huoWuEt.getText().toString();
			String getLPrice = minPiceEt.getText().toString();
			// 价格区间中某项不填，则随意给个默认值，为配合服务器检查参数规则
			// if (minPiceEt.getText().length() <= 0) {
			// getLPrice = "0.1";
			// }
			String getHPrice = maxPiceEt.getText().toString();
			// if (maxPiceEt.getText().length() <= 0) {
			// getHPrice = "1000";
			// }
			String getEShipPort = jiChuanGangEt.getText().toString();
			String getEShipTime = jiChuanRiQiBt.getText().toString();
			InitDatasDaoImpl.submitShipOrderAction(THIS, spu.getShip_id(),
					getLoadton, getStartPort, getEndPort, getEndTime,
					getCargoTypes, getHPrice, getLPrice, getEShipPort,
					getEShipTime, spu.getShip_name(), spu.getShipOrderTaskId());

		} catch (Exception e) {
			FunctionOfActivity.makeToaskShow(THIS, "提交异常");
		}
	}

	public void initWheelDate(final Button mText) {
		/**
		 * 初始化显示时间
		 */
		int year = 0;
		int month = 0;
		int day = 0;
		try {
			String thisDate = mText.getText().toString();
			year = Integer
					.parseInt(thisDate.substring(0, thisDate.indexOf("-")));
			month = Integer.parseInt(thisDate.substring(
					thisDate.indexOf("-") + 1, thisDate.lastIndexOf("-")));
			day = Integer.parseInt(thisDate.substring(
					thisDate.lastIndexOf("-") + 1, thisDate.length()));
		} catch (Exception e) {
			year = Integer.parseInt(FunctionOfActivity.getYearFromDate());
			month = Integer.parseInt(FunctionOfActivity.getMonthFromDate());
			day = Integer.parseInt(FunctionOfActivity.getDayFromDate());

		}
		// 年月日时间选择器
		DatePickerDialog datePickerLog = new DatePickerDialog(THIS,
				new OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						// TODO Auto-generated method
						// stub
						int mountOfYearShow = monthOfYear + 1;
						String month = FunctionOfActivity
								.addZero(mountOfYearShow + "");
						String day = FunctionOfActivity
								.addZero(dayOfMonth + "");
						mText.setText(year + "-" + month + "-" + day);
					}
				}, year, month - 1, day);
		datePickerLog.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			FunctionOfActivity.progressDialogShow(THIS);
			startActivity(new Intent(THIS, ShipOrderActivity.class));
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case RESULT_OK:
			Bundle b = data.getExtras(); // data为B中回传的Intent
			String str = b.getString("infoPort");// str即为回传的值
			switch (requestCode) {
			case 1:
				jiChuanGangEt.setText(str);
				break;
			case 2:
				qiYunDiEt.setText(str);
				break;
			case 3:
				muDiDiEt.setText(str);
				break;
			default:
				break;
			}

			break;
		default:
			break;
		}
	}

	/**
	 * 點擊EditText以外的區域后鍵盤隱藏
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {

			// 获取当前获得当前焦点所在View
			View view = getCurrentFocus();
			if (FunctionOfActivity.isClickEt(view, event)) {

				// 如果不是edittext，则隐藏键盘

				InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				if (inputMethodManager != null) {
					// 隐藏键盘
					inputMethodManager.hideSoftInputFromWindow(
							view.getWindowToken(), 0);
				}
			}
			return super.dispatchTouchEvent(event);
		}
		/**
		 * 看源码可知superDispatchTouchEvent 是个抽象方法，用于自定义的Window
		 * 此处目的是为了继续将事件由dispatchTouchEvent(MotionEvent
		 * event)传递到onTouchEvent(MotionEvent event) 必不可少，否则所有组件都不能触发
		 * onTouchEvent(MotionEvent event)
		 */
		if (getWindow().superDispatchTouchEvent(event)) {
			return true;
		}
		return onTouchEvent(event);
	}
}
